package com.szl.yeb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.szl.yeb.common.constant.MsgConstant;
import com.szl.yeb.common.R;
import com.szl.yeb.common.PageResult;
import com.szl.yeb.entity.*;
import com.szl.yeb.service.*;
import com.szl.yeb.utils.ResponseProcessor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Employee)表控制层
 *
 * @author szl
 * @since 2022-08-24 16:21:24
 */
@Api(tags = "员工管理接口(EmployeeController)")
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private NationService nationService;

    @Autowired
    private PoliticsStatusService politicsStatusService;

    @Autowired
    private JoblevelService joblevelService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PositionService positionService;

    @ApiOperation("分页查询所有员工信息")
    @GetMapping("/")
    public PageResult getAll(@RequestParam(defaultValue = "1") Integer currentPage,
                             @RequestParam(defaultValue = "10") Integer size,
                             Employee employee,
                             LocalDate[] engageDateScope
    ) {
        return employeeService.getPage(currentPage, size, employee, engageDateScope);
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nation")
    public R<Object> getNations() {
        return R.obj(nationService.list());
    }

    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsStatus")
    public R<Object> getPoliticsStatuses() {
        return R.obj(politicsStatusService.list());
    }

    @ApiOperation("获取所有部门")
    @GetMapping("/department")
    public R<Object> getDepartments() {
        return R.obj(departmentService.list());
    }

    @ApiOperation("获取所有职称")
    @GetMapping("/joblevel")
    public R<Object> getJoblevels() {
        return R.obj(joblevelService.list());
    }

    @ApiOperation("获取所有职位")
    @GetMapping("/position")
    public R<Object> getPositions() {
        return R.obj(positionService.list());
    }

    @ApiOperation("获取最大工号")
    @GetMapping("/maxWorkId")
    public R<Object> getMaxWorkId() {
        return R.obj(employeeService.getMaxWorkId());
    }

    @ApiOperation("添加员工信息")
    @PostMapping("/")
    public R<Object> addEmployee(@RequestBody Employee employee) {
        return ResponseProcessor.getResWithMsg(employeeService.addEmployee(employee), MsgConstant.ADD);
    }

    @ApiOperation("添加员工信息")
    @PutMapping("/")
    public R<Object> updateEmployee(@RequestBody Employee employee) {
        return ResponseProcessor.getResWithMsg(employeeService.updateById(employee), MsgConstant.UPDATE);
    }

    @ApiOperation("删除员工信息")
    @DeleteMapping("/{id}")
    public R<Object> deleteEmployee(@PathVariable Integer id) {
        return ResponseProcessor.getResWithMsg(employeeService.removeById(id), MsgConstant.DELETE);
    }

    @ApiOperation("批量删除员工信息")
    @DeleteMapping("/")
    public R<Object> deleteEmployees(@RequestParam List<Integer> ids) {
        return ResponseProcessor.getResWithMsg(employeeService.removeBatchByIds(ids), MsgConstant.DELETE);
    }

    @ApiOperation("导出员工信息")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployees(HttpServletResponse response) {

        List<Employee> employees = employeeService.getFilledEmployees();

        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);

        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employees);

        try (ServletOutputStream out = response.getOutputStream()) {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("导入员工信息")
    @PostMapping("/import")
    public R<Object> importEmployees(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);

        //将集合转换成map,key是实体的name,value是实体自身
        List<Nation> nations = nationService.list();
        Map<String, Nation> nationMap = nations.stream().collect(Collectors.toMap(Nation::getName, nation -> nation));

        List<PoliticsStatus> politicsStatuses = politicsStatusService.list();
        Map<String, PoliticsStatus> politicsStatusMap = politicsStatuses.stream().collect(Collectors.toMap(PoliticsStatus::getName, politicsStatus -> politicsStatus));

        List<Department> departments = departmentService.list();
        Map<String, Department> departmentMap = departments.stream().collect(Collectors.toMap(Department::getName, department -> department));

        List<Joblevel> joblevels = joblevelService.list();
        Map<String, Joblevel> joblevelMap = joblevels.stream().collect(Collectors.toMap(Joblevel::getName, joblevel -> joblevel));

        List<Position> positions = positionService.list();
        Map<String, Position> positionMap = positions.stream().collect(Collectors.toMap(Position::getName, position -> position));

        List<Employee> employees = null;
        try {
            employees = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);

            employees = employees.stream().peek(employee -> {
                if (employee.getNation() != null) {
                    employee.setNationId(nationMap.get(employee.getNation().getName()).getId());
                }
                if (employee.getDepartment() != null) {
                    employee.setPoliticId(politicsStatusMap.get(employee.getPoliticsStatus().getName()).getId());
                }
                if (employee.getDepartment() != null) {
                    employee.setDepartmentId(departmentMap.get(employee.getDepartment().getName()).getId());
                }
                if (employee.getJoblevel() != null) {
                    employee.setJobLevelId(joblevelMap.get(employee.getJoblevel().getName()).getId());
                }
                if (employee.getPosition() != null) {
                    employee.setPosId(positionMap.get(employee.getPosition().getName()).getId());
                }
            }).collect(Collectors.toList());

        } catch (Exception e) {
            e.printStackTrace();
        }


        boolean result = employeeService.saveBatch(employees);
        if (!result) {
            //设置HttpStatus 用户前端上传组件判断
            response.setStatus(500);
            return R.errMsg("导入失败");
        }
        return R.okMsg("导入成功");

    }

}

